<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        position: relative;
        margin: 0 auto;
        width: 500px;
        height: 500px;
        background: lightgray;
      }
      #block {
        width: 100px;
        height: 100px;
        position: absolute;
        left: 200px;
        top: 200px;
        background: #f40;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div id="block"></div>
    </div>
    <script>
      function getRandom(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      }

      var xSpeed = 2,
        ySpeed = 1;
      var x = 200,
        y = 200;
      var block = document.getElementById('block');
      // 改变背景颜色
      function changeBg() {
        block.style.background =
          'rgb(' +
          getRandom(0, 256) +
          ', ' +
          getRandom(0, 256) +
          ', ' +
          getRandom(0, 256) +
          ')';
      }
      setInterval(function () {
        // 移动
        x += xSpeed;
        y += ySpeed;
        // 限制范围
        if (x < 0) {
          x = 0;
          xSpeed = -xSpeed;
          changeBg()
        } else if (x > 400) {
          x = 400;
          xSpeed = -xSpeed;
          changeBg()
        }

        if (y < 0) {
          y = 0;
          ySpeed = -ySpeed;
          changeBg()
        } else if (y > 400) {
          y = 400;
          ySpeed = -ySpeed;
          changeBg()
        }
        block.style.left = x + 'px';
        block.style.top = y + 'px';
      }, 10);
    </script>
  </body>
</html>
